--[[
   @classmod Map
   a Map assemble layers and markers
   no marker can be added without creating a map first
   a map has a name, a width, and a height (in tile units)
]]

local bitser = require('lib.bitser')
local Marker = require('src.gen.marker')
local lume = require('lib.lume')
local Layers = require('src.gen.layers')

return Class {
   _name = "Map",
   
   init = function (self, name, w, h)
      self.name = name or "untitledmap"
      self.w, self.h = w, h
      self.layers = Layers()
      self.markers = {}
   end,
   
   update = function (self)
      
   end,
   
   draw = function (self)
      self.layers:draw()
      if self.debug then
	 lume.each(self.markers, function (m) m:draw() end)
      end
   end,
   
   marker_add = function (self, name, x, y)
      local x = x or 0
      local y = y or 0
      if not name then return "marker need a name" end
      local m = self:marker_get(name)
      local n = self:marker_get(x, y)
      if m then
	 local err = "a marker with name %s already exists at x: %i y: %i"
	 return string.format(err, m.name, m.x, m.y)
      end
      if n then
	 local err = "a marker with position %i %i already exists with name "
	 return string.format(err, n.x, n.y, n.name)
      end
      table.insert(self.markers, Marker(name, x, y))
      return string.format("added marker %s at x: %i y:%i", name, x, y)
   end,
   
   marker_get = function (self, v, u)
      for k, m in ipairs(self.markers) do
	 if type(v) == "string" then
	    if m.name == v then return m end
	 elseif type(v) == "number" and type(u) == "number" then
	    if m.x == v and m.y == u then return m end
	 end
      end
      return nil
   end,
   
   get_dimensions = function (self)
      return self.w, self.h
   end,
   
   make_layer = function (self, name, z)
      local l = self.layers:add(name, z, self.w, self.h)
   end,
}
